const { Readable, Transform, Writable } = require("stream");
const fs = require("fs");

// Readable stream to read data from the object array
class ObjectReader extends Readable {
  constructor(objectArray, options) {
    super({ objectMode: true, ...options });
    this.objectArray = objectArray;
    this.index = 0;
  }

  _read() {
    if (this.index < this.objectArray.length) {
      const chunk = JSON.stringify(this.objectArray[this.index++]);
      this.push(chunk);
    } else {
      this.push(null);
    }
  }
}

// Transform stream to process the objects
class ObjectProcessor extends Transform {
  constructor(processFunc, options) {
    super(options);
    this.processFunc = processFunc;
  }
  _transform(chunk, encoding, callback) {
    // Process the object (e.g., perform some computation or transformation)
    this.push(this.processFunc(chunk));
    callback();
  }
}

// Writable stream to output the processed objects to a file
class ObjectWriter extends Writable {
  constructor(outputFilePath, options) {
    super(options);
    this.outputFilePath = outputFilePath;
  }

  _write(chunk, encoding, callback) {
    // Output the processed object to the specified file
    fs.appendFile(this.outputFilePath, chunk + "\n", (err) => {
      if (err) {
        console.error("Error writing to file:", err);
      }
      callback();
    });
  }
}

const write2output = (dataArray, outputFile) => {
  // Create instances of the streams
  const reader = new ObjectReader(dataArray);
  const processor = new ObjectProcessor((chunk) => {
    const parsedData = JSON.parse(chunk);
    const { folderId, filename, result, resultType, time, memory } = parsedData;
    return `${folderId}, ${filename}, ${result}, ${resultType}, ${time}, ${memory}`;
  });
  const writer = new ObjectWriter(outputFile);

  return new Promise((resolve, reject) => {
    // Pipe the streams together to process and output the objects
    reader
      .pipe(processor)
      .pipe(writer)
      .on("finish", resolve)
      .on("error", reject);
  });
};

// async function output(dataArray, outputFilePath) {
//   const titleLine = "Folder, Filename, Result\n";
//   fs.truncate(outputFilePath, 0, (err) => {});
//   fs.appendFile(outputFilePath, titleLine, (err) => {});
//   await write2output(dataArray, outputFilePath);
//   await write2output(dataArray, outputFilePath);
//   await write2output(dataArray, outputFilePath);
// }

module.exports = {
  write2output,
};
